package patrol.mobile.com.mobilepatrol.api;

import android.util.Log;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.bean.ResultInfo;
import patrol.mobile.com.mobilepatrol.utils.Compress;


public class ApiClient {
    private static final String TAG=ApiClient.class.getSimpleName();

	public static final String UTF_8 = "UTF-8";

	private final static int TIMEOUT_CONNECTION = 60000*5;
	private final static int TIMEOUT_SOCKET = 60000*5;

    public final static String REQ_POST="post";
    public final static String REQ_GET="get";

	private static String appUserAgent;

	private static String getUserAgent(PatrolApp appContext) {
		if(appUserAgent == null || appUserAgent == "") {
			StringBuilder ua = new StringBuilder("Jie0.com");
			ua.append('/'+appContext.getPackageInfo().versionName+'_'+appContext.getPackageInfo().versionCode);//App版本
			ua.append("/Android");//手机系统平台
			ua.append("/"+android.os.Build.VERSION.RELEASE);//手机系统版本
			ua.append("/"+android.os.Build.MODEL); //手机型号
			ua.append("/"+appContext.getAppId());//客户端唯一标识
			appUserAgent = ua.toString();
		}
		return appUserAgent;
	}

	private static HttpClient getHttpClient() {
        HttpClient httpClient = new HttpClient();
		// 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
		httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        // 设置 默认的超时重试处理策略
		httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		// 设置 连接超时时间
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT_CONNECTION);
		// 设置 读数据超时时间
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET);
		// 设置 字符集
		httpClient.getParams().setContentCharset(UTF_8);
		return httpClient;
	}

	private static GetMethod getHttpGet(String url, String userAgent) {
		GetMethod httpGet = new GetMethod(url);
		// 设置 请求超时时间
		httpGet.getParams().setSoTimeout(TIMEOUT_SOCKET);
		httpGet.setRequestHeader("Referer", url);
		httpGet.setRequestHeader("Connection","Keep-Alive");
		httpGet.setRequestHeader("User-Agent", userAgent);
		return httpGet;
	}

	private static PostMethod getHttpPost(String url, String userAgent) {
		PostMethod httpPost = new PostMethod(url);
		// 设置 请求超时时间
		httpPost.getParams().setSoTimeout(TIMEOUT_SOCKET);
		httpPost.setRequestHeader("Referer", url);
		httpPost.setRequestHeader("Connection","Keep-Alive");
        httpPost.setRequestHeader("User-Agent", userAgent);
		return httpPost;
	}

	private static String _MakeURL(String p_url, Map<String, Object> params) {
        if(params==null)
            return p_url;
		StringBuilder url = new StringBuilder(p_url);
		if(url.indexOf("?")<0)
			url.append('?');

		for(String name : params.keySet()){
			url.append('&');
			url.append(name);
			url.append('=');
			try {
				url.append(URLEncoder.encode(String.valueOf(params.get(name)),"utf-8"));
			} catch (UnsupportedEncodingException e) {

				e.printStackTrace();
			}
		}

		return url.toString().replace("?&", "?");
	}

	/**
	 * get请求URL
	 * @param url
	 * @throws AppException
	 */
	private static String http_get(PatrolApp appContext, String url) throws AppException {
        Log.e(TAG,"request get:"+url);
		HttpClient httpClient = null;
		GetMethod httpGet = null;

		String responseValue = "";

			try
			{
				httpClient = getHttpClient();
				httpGet = getHttpGet(url, getUserAgent(appContext));
				httpGet.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
				int statusCode = httpClient.executeMethod(httpGet);
				if (statusCode != HttpStatus.SC_OK) {
					throw AppException.http(statusCode);
				}
                responseValue = Compress.decompressByteArray(httpGet.getResponseBody());
				Log.i(TAG,"\nXMLDATA=====>"+url+"\n"+responseValue);
			} catch (HttpException e) {
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
                // 释放连接
                if(httpGet!=null)
                    httpGet.releaseConnection();
                httpClient = null;
            }

		return responseValue;
	}

	/**
	 * 公用post方法
	 * @param appContext
	 * @param url
	 * @param params
	 * @throws AppException
	 */
	private static String _post(PatrolApp appContext, String url, Map<String, Object> params, Map<String,File> files) throws AppException {
        Log.e(TAG,"request post:"+url);

		HttpClient httpClient;
		PostMethod httpPost = null;

        //post表单参数处理
        int length = (params == null ? 0 : params.size()) + (files == null ? 0 : files.size());
        Part[] parts = new Part[length];
        int i = 0;
        if(params != null)
            for(String name : params.keySet()){
                parts[i++] = new StringPart(name, String.valueOf(params.get(name)), UTF_8);
                //	System.out.println("post_key==> "+name+"    value==>"+String.valueOf(params.get(name)));
            }

        if(files != null)
            for(String file : files.keySet()){
                try {
                    parts[i++] = new FilePart("file", files.get(file));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                //System.out.println("post_key_file==> "+file);
            }

		String responseValue = "";
			try
			{
				httpClient = getHttpClient();
				httpPost = getHttpPost(url,getUserAgent(appContext));
				httpPost.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
                httpPost.setRequestEntity(new MultipartRequestEntity(parts,httpPost.getParams()));

		        int statusCode = httpClient.executeMethod(httpPost);

		        if(statusCode != HttpStatus.SC_OK)
		        {
		        	throw AppException.http(statusCode);
		        }
                Log.i(TAG,"\nDATA=====>"+url+"\n"+httpPost.getResponseBodyAsString());
		     	responseValue = Compress.decompressByteArray(httpPost.getResponseBody());
               Log.i(TAG,"\nDATA=====>"+url+"\n"+responseValue);

			} catch (HttpException e) {
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				// 释放连接
                if(httpPost!=null)
				    httpPost.releaseConnection();
				httpClient = null;
			}


        return responseValue;
	}

	public static ResultInfo getResultInfo(PatrolApp ac, String url, String requestMode, Map<String, Object> params, Map<String,File> files) throws AppException {
        ResultInfo info = null;

        if(requestMode.equals(REQ_GET)){
            info= DataUtil.parseJsonInfo(http_get(ac,_MakeURL(url, params)),ResultInfo.class);
        }else if(requestMode.equals(REQ_POST)) {
            info = DataUtil.parseJsonInfo(_post(ac, url,params,files), ResultInfo.class);
        }

        return info;
    }

}
